<template>
    <div class="pay">
        <div class="pay-top">
            <span @click="handleToRoute('/pages/pay/record')">充值记录</span>
            <span @click="handleToRoute('/pages/pay/used')">消耗记录</span>
        </div>
        <div class="card card1">
            <div class="title">账户余额</div>
            <div class="count">{{ count }}元</div>
        </div>
        <div class="card card2">
            <div class="card2-top">
                <div class="title">
                    充值
                </div>
            </div>
            <div class="card2-middle">
                <div @click="handleCheckPay(item)" :class="['value-item', currentPay === item.value ? 'active' : '']" v-for="item in payList" :key="item.value">
                    <div>
                        <span v-if="item.value !== 100">充</span>{{ item.value }}<span class="unit">元</span>
                    </div>
                    <div v-if="item.value2" style="font-size: 12px;color: #000000;text-align: left">
                        赠{{ item.value2 }}元
                    </div>
                </div>
            </div>
            <div class="submit-btn-box">
                <div class="submit-btn" @click="handleSubmit" :style="{ backgroundColor: currentPay ? '#5581FA' : '#5581faa1'}">确认充值</div>
            </div>
        </div>
    </div>
</template>

<script>
import {payRequest, systemRequest} from "@/api";

export default {
    name: "pay",
    data() {
      return {
          count: '89990',
          payList: [
              {
                  value: 100,
                  value2: 0
              },
              {
                  value: 300,
                  value2: 10
              },
              {
                  value: 500,
                  value2: 20
              },
              {
                  value: 1000,
                  value2: 100
              },
              {
                  value: 2000,
                  value2: 500
              },
              {
                  value: 5000,
                  value2: 2000
              }
              
          ],
          currentPay: 0,
          isPaySuccessed: false,
          isRequestClosed: false
      }
    },
    created() {
        this.getAccountInfo()
    },
    methods: {
        getAccountInfo() {
            payRequest.accountInfo().then(res => {
                this.count = res.data.balance ? (res.data.balance / 100).toFixed(2) : 0
            })
        },
        handleToRoute(url) {
            uni.navigateTo({
                url
            })
        },
        handleCheckPay(item) {
            this.currentPay = item.value
        },
        async handleSubmit() {
            if (!this.currentPay) return
    
            /**
             *  通过code 获取openid
             */
            const code = await this.getCode()
            console.log(code)
            const openIDRes = await systemRequest.getOpenId(code)
            const openId = openIDRes.data.openId
            /**
             *  通过openid创建充值订单
             */
            const orderInfoRes = await payRequest.createOrder({amount: this.currentPay * 100, openId: openId })
            /**
             *  唤醒支付
             */
            await this.openPayModal(orderInfoRes.data)
            console.log('请求定时器')
            setTimeout(() => {
                this.getAccountInfo()
            },1000)
            /**
             * 支付成功 轮询问是否成功
             *  上一次轮询请求结束 && 未支付成功
             */
            // let interval = setInterval(() => {
            //     if (!this.isRequestClosed && !this.isPaySuccessed) {
            //         payRequest.askCallbackSuccess(orderInfoRes.data.outTradeNo).then(res => {
            //             // 处理中
            //            if (res.data.status === 4)  {
            //                this.isRequestClosed = true
            //                this.isPaySuccessed = true
            //                interval = 0
            //                clearInterval(interval)
            //                /**
            //                 * 刷新页面
            //                 */
            //                this.getAccountInfo()
            //            } else if (res.data.status !== 0) {
            //                this.isRequestClosed = true
            //                this.isPaySuccessed = true
            //                interval = 0
            //                clearInterval(interval)
            //                wx.showToast({
            //                    title: '充值失败'
            //                })
            //            }
            //         }).catch(() => {
            //             this.isRequestClosed = true
            //             this.isPaySuccessed = false
            //         })
            //     }
            // },500)
            
        },
        getCode() {
            return new Promise((resolve,reject) => {
                wx.login().then(res => {
                    console.log(res)
                    if (res.errMsg === 'login:ok') {
                        resolve(res.code)
                    } else {
                        wx.showToast({
                            icon:'none',
                            title: '获取用户信息失败'
                        })
                        reject()
                    }
                })
            })
        },
        openPayModal(orderInfo) {
            return new Promise((resolve,reject) => {
                console.log('调用支付')
                wx.requestPayment({
                    // 时间戳
                    timeStamp: orderInfo.timestamp.toString(),
                    // 随机字符串
                    nonceStr: orderInfo.nonceStr,
                    // 统一下单接口返回的 prepay_id 参数值
                    package: orderInfo.package,
                    // 签名类型
                    signType: orderInfo.signType,
                    // 签名
                    paySign: orderInfo.paySign,
                    // 调用成功回调
                    success (res) {
                        console.log('支付成功',res)
                        wx.showToast({
                            title: '支付成功'
                        })
                        resolve()
                    },
                    // 失败回调
                    fail (res) {
                        if (res.errMsg === 'requestPayment:fail cancel') {
                            wx.showToast({
                                title: '取消支付'
                            })
                        } else {
                            wx.showToast({
                                title: '支付失败'
                            })
                        }
                        reject()
                    },
                    // 接口调用结束回调
                    complete (res) {
                        console.log('取消支付',res)
                    }
                })
            })
            
        }
    }
}
</script>

<style lang="less">
.pay {
    height: 100vh;
    padding: 16px;
    overflow: hidden;
    background-color: #FBFBFB;
    .pay-top {
        display: flex;
        justify-content: space-between;
        font-size: 14px;
        color: #999999;
        line-height: 14px;
        margin-bottom: 16px;
    }
    .card {
        background-color: #FFFFFF;
        border-radius: 8px;
        width: 100%;
        min-height: 100px;
        padding: 16px;
        margin-bottom: 8px;
    }
    .card1 {
        padding: 20px;
        text-align: center;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        .title {
            color: #999999;
            font-size: 14px;
            line-height: 14px;
            margin-bottom: 10px;
        }
        .count {
            color: red;
            font-size: 16px;
            line-height: 16px;
        }
    }
    .card2 {
        .card2-top {
            display: flex;
            justify-content: space-between;
            align-items: center;
            .title {
                font-size: 14px;
                color: #000000;
                margin-bottom: 10px;
            }
        }
        .card2-middle {
            display: flex;
            flex-wrap: wrap;
            justify-content: space-between;
            margin-bottom: 30px;
            .value-item {
                border: 1px solid transparent;
                &.active {
                    border-color: #5581FA;
                }
                width: 32%;
                padding: 10px 4px;
                margin-bottom: 8px;
                border-radius: 6px;
                background-color: #FBFBFB;
                color: #5581FA;
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                font-size: 14px;
                .unit {
                    font-size: 12px;
                }
            }
        }
        .submit-btn-box {
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 0 80px;
        
            .submit-btn {
                width: 100%;
                height: 40px;
                line-height: 40px;
                font-size: 14px;
                text-align: center;
                color: #FFFFFF;
                background-color: #5581FA;
                border-radius: 6px;
            }
        }
    }
}
</style>